package com.payment.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.enums.CompanyId;
import com.payment.common.type.PaymentOrderType;
import com.payment.common.utils.StringUtils;
import com.payment.system.domain.Acq;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.PaymentOrder;
import com.payment.system.mapper.AcqMapper;
import com.payment.system.mapper.MerchantIncreaseLimitMapper;
import com.payment.system.mapper.MerchantMapper;
import com.payment.system.mapper.PaymentOrderMapper;
import com.payment.system.mapper.SystemConfigMapper;
import com.payment.system.service.IAbroadExchangeService;
import com.payment.system.util.GuangGuUtil;
import com.payment.system.vo.AbroadOrderVo;
import com.payment.system.vo.CreditCardVo;

/**
 * @author fuzhili
 * @Description: 境外消费
 * @date 2019/11/23 9:23
 */
@Service
public class AbroadExchangeServiceImpl implements IAbroadExchangeService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AbroadExchangeServiceImpl.class);
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private AcqMapper acqMapper;
    @Autowired
    private SystemConfigMapper configMapper;
    @Autowired
    private MerchantIncreaseLimitMapper merchantIncreaseLimitMapper;
    /**
     * 获取汇率列表
     *
     * @return
     */
    @Override
    public AjaxResult selectRateList() {
        try {
            JSONObject jsonObject = GuangGuUtil.getAbroadExchangeRate();
            if (jsonObject == null) {
                return AjaxResult.error(3, "获取汇率列表，请重试！");
            }
            String resCode = jsonObject.getString("res_code");
            String rateList = jsonObject.getString("list");
            if (("YQB000000").equals(resCode)) {
                return AjaxResult.successAndData("获取汇率列表成功", rateList);
            } else {
                LOGGER.error("【获取汇率列表失败】{}", jsonObject.getString("res_msg"));
                return AjaxResult.error(1, jsonObject.getString("res_msg"));
            }
        } catch (Exception e) {
            LOGGER.error("【获取汇率列表异常】{}", e);
            return AjaxResult.error(1, "获取汇率列表异常");
        }
    }

    /**
     * 获取商品列表
     *
     * @return
     */
    @Override
    public AjaxResult selectGoodsList(String currercyCode, BigDecimal cnyAmount) {
        if (StringUtils.isEmpty(currercyCode) || cnyAmount == null) {
            return AjaxResult.error(1, "缺失必要参数");
        }

        try {
            JSONObject jsonObject = GuangGuUtil.getAbroadGoods();
            String resCode = jsonObject.getString("res_code");
            JSONArray goodsList = jsonObject.getJSONArray("list");
            if (("YQB000000").equals(resCode) && goodsList != null && goodsList.size() > 0) {
                JSONArray goodsListNow = new JSONArray();
                for (int i = 0; i < goodsList.size(); i++) {
                    JSONObject jsonObjectData = (JSONObject) goodsList.get(i);
                    String currercyCodeNow = jsonObjectData.getString("currercyCode");
                    if (currercyCode.equals(currercyCodeNow)) {
                        BigDecimal foreignAmt = cnyAmount.multiply(jsonObjectData.getBigDecimal("price"));
                        jsonObjectData.put("foreignAmt", foreignAmt);
                        goodsListNow.add(jsonObjectData);
                    }
                }
                return AjaxResult.successAndData("获取商品列表成功", goodsListNow);
            } else {
                LOGGER.error("【获取商品列表失败】{}", jsonObject.getString("res_msg"));
                return AjaxResult.error(1, jsonObject.getString("res_msg"));
            }
        } catch (Exception e) {
            LOGGER.error("【获取商品列表异常】{}", e);
            return AjaxResult.error(1, "获取商品列表异常");
        }
    }

	/**
	 * 境外下单
	 */
	@Override
	public AjaxResult placeOrder(String merId, String ip, String currercyCode, BigDecimal orderAmount, Integer number,
			BigDecimal exchangeRate, BigDecimal foreignAmt, String goodsNo, String bankCardNo) {
		if (StringUtils.isEmpty(merId) || StringUtils.isEmpty(ip) || StringUtils.isEmpty(currercyCode)
				|| StringUtils.isEmpty(goodsNo) || orderAmount == null || number == null || exchangeRate == null
				|| foreignAmt == null || StringUtils.isEmpty(bankCardNo)) {
			return AjaxResult.error(1, "缺失必要参数");
		}
		Merchant merchant = merchantMapper.selectMerchantById(merId);
		if (merchant == null || StringUtils.isEmpty(merchant.getAcqMerchantNo())) {
			return AjaxResult.error(1, "用户不存在或未签约通道");
		}
		Acq acq = acqMapper.selectAcqByCode(CompanyId.ABROAD_EXCHANGE.getCode());
		if (acq == null) {
			return AjaxResult.error(1, "暂未找到境外消费的渠道");
		}
		// 订单预处理
		AbroadOrderVo abroadOrderVo = saveOrder(merchant, acq, currercyCode, ip, orderAmount, number, exchangeRate,
				foreignAmt, goodsNo, bankCardNo);
		try {
			JSONObject jsonObject = GuangGuUtil.abroadOrderPay(abroadOrderVo);
			String resCode = jsonObject.getString("res_code");
			String url = jsonObject.getString("url");
			if (("YQB000000").equals(resCode)) {
				System.out.println(url);
				return AjaxResult.successAndData("境外下单成功", url);
			} else {
				LOGGER.error("【境外下单成功失败】{}", jsonObject.getString("res_msg"));
				return AjaxResult.error(1, jsonObject.getString("res_msg"));
			}
		} catch (Exception e) {
			LOGGER.error("【境外下单成功异常】{}", e);
			return AjaxResult.error(1, "境外下单成功异常");
		}
	}

    /**
     * 订单预处理
     */
	private AbroadOrderVo saveOrder(Merchant merchant, Acq acq, String currercyCode, String ip, BigDecimal orderAmount,
			Integer number, BigDecimal exchangeRate, BigDecimal foreignAmt, String goodsNo,String bankCardNo) {
        /** 根据信用卡id查询信用卡信息 */
        CreditCardVo creditCardId = merchantIncreaseLimitMapper.selectCardVoById(bankCardNo);
        BigDecimal rate = BigDecimal.ONE;
        PaymentOrder paymentOrder = new PaymentOrder();
        paymentOrder.setId(StringUtils.randomUUID());
        String orderNo = StringUtils.createNum();
        paymentOrder.setOrderNo(orderNo);
        paymentOrder.setMerchantId(merchant.getId());
        paymentOrder.setMerchantName(merchant.getMerchantCnName());
        paymentOrder.setOrderStatus(0);
        paymentOrder.setOrderType(PaymentOrderType.TEN.getCode());
        paymentOrder.setAcqId(acq.getId());
        paymentOrder.setAcqCode(acq.getAcqCode());
        paymentOrder.setAcqName(acq.getAcqName());
        paymentOrder.setAmountMoney(orderAmount);
        paymentOrder.setCostRateMoney(acq.getCostRate().multiply(orderAmount));
        paymentOrder.setRateMoney(rate.multiply(orderAmount));
        BigDecimal profitRate = rate.subtract(acq.getCostRate());
        paymentOrder.setProfitMoney(profitRate.multiply(orderAmount));
        paymentOrder.setClearingStatus(1);
        paymentOrder.setCreateTime(new Date());
        paymentOrder.setIp(ip);
        paymentOrder.setCreditNumber(creditCardId.getBankAccount());
        paymentOrder.setBankName(creditCardId.getBankName());
        //保存本地订单
        paymentOrderMapper.insertPaymentOrder(paymentOrder);
        AbroadOrderVo abroadOrderVo = new AbroadOrderVo();
        abroadOrderVo.setSeriaNo(orderNo);
        abroadOrderVo.setCompanyId(acq.getAcqCode());
        abroadOrderVo.setUserId(merchant.getAcqMerchantNo());
        abroadOrderVo.setRate(rate.multiply(new BigDecimal("100")));
        abroadOrderVo.setUserName(merchant.getMerchantCnName());
        abroadOrderVo.setCurrercyCode(currercyCode);
        abroadOrderVo.setOrderAmount(orderAmount);
        abroadOrderVo.setNumber(number);
        abroadOrderVo.setExchangeRate(exchangeRate);
        abroadOrderVo.setForeignAmt(foreignAmt);
        abroadOrderVo.setGoodsNo(goodsNo);
        abroadOrderVo.setBankCardNo(creditCardId.getBankAccount());
        return abroadOrderVo;
    }


}
